package pattern10.eventcommission;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 处理的事件类
 * 通过反射获取到执行方法的对象和方法名方法参数
 *
 * @author wdl
 */
public class Event {
    /**
     * 要执行方法的对象
     */
    private Object object;
    /**
     * 要执行方法的方法名
     */
    private String methodName;
    /**
     * 要执行方法的参数
     */
    private Object[] params;

    public Object getObject() {
        return object;
    }

    public void setObject(Object object) {
        this.object = object;
    }

    public String getMethodName() {
        return methodName;
    }

    public void setMethodName(String methodName) {
        this.methodName = methodName;
    }

    public Object[] getParams() {
        return params;
    }

    public void setParams(Object[] params) {
        this.params = params;
    }

    /**
     * 要执行方法的参数类型
     */
    private Class[] paramTypes;

    public Class[] getParamTypes() {
        return paramTypes;
    }

    public void setParamTypes(Class[] paramTypes) {
        this.paramTypes = paramTypes;
    }

    /**
     * 根据参数列表生成参数类型列表
     *
     * @param params 参数列表
     */
    private void contractParamTypes(Object[] params) {
        this.paramTypes = new Class[params.length];
        //遍历获取每个参数的类型
        for (int i = 0; i < params.length; i++) {
            this.paramTypes[i] = params[i].getClass();
        }
    }

    /**
     * 构造函数
     */
    public Event() {

    }

    public Event(Object object, String methodName, Object[] params) {
        this.object = object;
        this.methodName = methodName;
        this.params = params;
        contractParamTypes(params);
    }

    /**
     * 执行该对象的该方法(这里使用反射)
     */
    public void invoke() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method method=object.getClass().getMethod(this.getMethodName(),this.getParamTypes());
        if (method==null){
            return;
        }
        method.invoke(this.getObject(),this.getParams());
    }
}
